<template>
  <div class="radar-chart">
    <!-- ECharts 雷达图 -->
    <div ref="chartRef" :style="{ width: width + 'px', height: height + 'px' }" class="mx-auto"></div>

    <!-- 统计信息 -->
    <div class="mt-4 grid grid-cols-3 gap-4 text-center">
      <div>
        <div class="text-lg font-bold text-blue-600">{{ averageScore }}</div>
        <div class="text-xs text-gray-500">平均分</div>
      </div>
      <div>
        <div class="text-lg font-bold text-red-600">{{ weaknessCount }}</div>
        <div class="text-xs text-gray-500">短板科目</div>
      </div>
      <div>
        <div class="text-lg font-bold text-green-600">{{ strengthCount }}</div>
        <div class="text-xs text-gray-500">优势科目</div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed, ref, onMounted, onUnmounted, watch } from 'vue'

// 定义props
const props = defineProps({
  subjects: {
    type: Array,
    required: true
  },
  width: {
    type: Number,
    default: 450
  },
  height: {
    type: Number,
    default: 350
  }
})

// 图表引用
const chartRef = ref(null)
let chart = null

// 统计信息
const averageScore = computed(() => {
  const total = props.subjects.reduce((sum, subject) => sum + subject.score, 0)
  return Math.round(total / props.subjects.length)
})

const weaknessCount = computed(() => {
  return props.subjects.filter(subject => subject.isWeakness).length
})

const strengthCount = computed(() => {
  return props.subjects.filter(subject => !subject.isWeakness).length
})

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return

  // 动态导入 ECharts
  import('echarts').then((echarts) => {
    chart = echarts.init(chartRef.value)
    updateChart()
  }).catch((error) => {
    console.error('Failed to load ECharts:', error)
    // 如果 ECharts 未安装，显示提示信息
    chartRef.value.innerHTML = `
      <div class="flex items-center justify-center h-full text-gray-500">
        <div class="text-center">
          <div class="i-mdi:chart-radar w-16 h-16 mx-auto mb-2"></div>
          <p>请先安装 ECharts: npm install echarts</p>
        </div>
      </div>
    `
  })
}

// 更新图表数据
const updateChart = () => {
  if (!chart) return

  const option = {
    title: {
      text: '各科目水平分布',
      left: 'center',
      top: 10,
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold',
        color: '#374151'
      }
    },
    tooltip: {
      trigger: 'item',
      backgroundColor: 'rgba(0, 0, 0, 0.8)',
      borderColor: 'transparent',
      borderRadius: 8,
      textStyle: {
        color: '#fff'
      },
      formatter: function (params) {
        const subject = props.subjects.find(s => s.name === params.name)
        if (subject) {
          const gapText = subject.gap > 0 ? `+${subject.gap}` : subject.gap
          const gapColor = subject.gap >= 0 ? '#10b981' : '#ef4444'
          return `
             <div style="padding: 12px; min-width: 200px;">
               <div style="font-weight: bold; font-size: 14px; margin-bottom: 8px; color: #fff;">
                 ${subject.name}
               </div>
               <div style="display: flex; justify-content: space-between; margin-bottom: 4px;">
                 <span style="color: #9ca3af;">当前分数:</span>
                 <span style="color: #fff; font-weight: bold;">${params.value}</span>
               </div>
               <div style="display: flex; justify-content: space-between; margin-bottom: 4px;">
                 <span style="color: #9ca3af;">班级平均:</span>
                 <span style="color: #fff;">${subject.averageScore}</span>
               </div>
               <div style="display: flex; justify-content: space-between;">
                 <span style="color: #9ca3af;">分数差距:</span>
                 <span style="color: ${gapColor}; font-weight: bold;">${gapText}</span>
               </div>
             </div>
           `
        }
        return params.name + ': ' + params.value
      }
    },
    radar: {
      indicator: props.subjects.map(subject => ({
        name: subject.name,
        max: 100,
        color: subject.isWeakness ? '#ef4444' : '#3b82f6'
      })),
      radius: '60%',
      center: ['50%', '60%'],
      splitNumber: 5,
      axisName: {
        color: '#374151',
        fontSize: 12,
        fontWeight: 500,
        backgroundColor: 'rgba(255, 255, 255, 0.8)',
        borderRadius: 4,
        padding: [4, 8]
      },
      splitLine: {
        lineStyle: {
          color: ['#e5e7eb'],
          width: 1,
          opacity: 0.6
        }
      },
      splitArea: {
        show: true,
        areaStyle: {
          color: ['rgba(59, 130, 246, 0.05)', 'rgba(59, 130, 246, 0.02)']
        }
      },
      axisLine: {
        lineStyle: {
          color: '#e5e7eb',
          width: 1
        }
      }
    },
    series: [
      {
        name: '科目成绩',
        type: 'radar',
        data: [
          {
            value: props.subjects.map(subject => subject.score),
            name: '当前成绩',
            itemStyle: {
              color: function (params) {
                const subject = props.subjects[params.dataIndex]
                return subject.isWeakness ? '#ef4444' : '#3b82f6'
              }
            },
            areaStyle: {
              color: 'rgba(59, 130, 246, 0.15)',
              opacity: 0.8
            },
            lineStyle: {
              color: '#3b82f6',
              width: 3
            },
            symbol: 'circle',
            symbolSize: function (value, params) {
              const subject = props.subjects[params.dataIndex]
              return subject.isWeakness ? 8 : 6
            },
            symbolColor: function (params) {
              const subject = props.subjects[params.dataIndex]
              return subject.isWeakness ? '#ef4444' : '#3b82f6'
            }
          }
        ]
      }
    ],
    color: ['#3b82f6', '#ef4444'],
    backgroundColor: 'transparent',
  }

  chart.setOption(option)
}

// 监听数据变化
watch(() => props.subjects, () => {
  if (chart) {
    updateChart()
  }
}, { deep: true })

// 监听尺寸变化
watch([() => props.width, () => props.height], () => {
  if (chart) {
    chart.resize()
  }
})

// 组件挂载时初始化图表
onMounted(() => {
  initChart()
})

// 组件卸载时销毁图表
onUnmounted(() => {
  if (chart) {
    chart.dispose()
    chart = null
  }
})
</script>

<style lang="scss" scoped>
.radar-chart {
  .echarts-for-vue {
    width: 100%;
    height: 100%;
  }
}
</style> 